package com.pap.datas.annotation;

import com.pap.base.util.string.StringUtilss;
import com.pap.datas.agent.dict.IDictAgent;
import com.pap.datas.dict.auto.entity.Dict;
import com.pap.datas.dict.auto.entity.DictDetail;
import com.pap.datas.dict.auto.mapper.DictDetailMapper;
import com.pap.obj.vo.logineduser.LoginedUserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 自定义参数解释器，返回当前登录用户的实体信息
 * @Auther: alexgaoyh
 * @Date: 2018/11/29 09:16
 * @Description:
 */
@Component
public class LoginedUserArgumentResolver implements HandlerMethodArgumentResolver {

    /**
     * TODO 后续此处可以替换为从redis 获取其他途径获取到登录用户的实体信息
     * 此处仅为可以从Bean工厂中获取到实例即可
     */
    @Autowired
    private DictDetailMapper dictDetailMapper;

    /**
     * 检查解析器是否支持解析该参数
     */
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        if(
            //如果该参数注解有@Logined
                parameter.getParameterAnnotation(LoginedUser.class)!=null&&
                        //如果该参数的类型为User
                        parameter.getParameterType()== LoginedUserVO.class
        ){
            //支持解析该参数
            return true;
        }
        return false;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter,
                                  ModelAndViewContainer mavContainer, NativeWebRequest webRequest,
                                  WebDataBinderFactory binderFactory) throws Exception {
        LoginedUserVO loginedUserVO = new LoginedUserVO();
        HttpServletRequest request= (HttpServletRequest) webRequest.getNativeRequest();
        String loginUserHeaderToekn = request.getHeader("TOKEN");
        if(StringUtilss.isNotEmpty(loginUserHeaderToekn)) {
            DictDetail dictDetail = dictDetailMapper.selectByPrimaryKey(loginUserHeaderToekn);
            if(dictDetail != null) {
                loginedUserVO.setId("alexgaoyh");
                loginedUserVO.setCode("alexgaoyh");
                loginedUserVO.setName("alexgaoyh");
            }
        }
        return loginedUserVO;
    }
}